import { useRef } from 'react'
import styles from './index.module.scss'
type Props = {
  type: '' | 'gender' | 'photo'
  close: () => void
  onUpdateName: (
    value: string | FormData,
    type: string,
    close: () => void
  ) => void
}
const gender = [
  { value: '0', text: '男' },
  { value: '1', text: '女' },
]
const photo = [
  { value: '', text: '拍照' },
  { value: '', text: '本地照片' },
]
const EditList = ({ close, onUpdateName, type }: Props) => {
  const fileRef = useRef<HTMLInputElement>(null)
  const list = type === 'gender' ? gender : photo
  const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    if (!e.target.files?.length) return
    // 后台需要 FormData 格式的参数 需要用new一个formData对象用append上传
    const formData = new FormData()
    formData.append('photo', e.target.files[0])
    onUpdateName(formData, type, close)
  }
  return (
    <div className={styles.root}>
      {list.map((item) => (
        <div
          key={item.text}
          className="list-item"
          onClick={() => {
            if (type === 'photo') {
              fileRef.current!.click()
            } else {
              return onUpdateName(item.value, type, close)
            }
          }}>
          {item.text}
        </div>
      ))}
      <div className="list-item" onClick={close}>
        取消
      </div>
      <input
        type="file"
        hidden
        ref={fileRef}
        onChange={(e) => handleChange(e)}
      />
    </div>
  )
}

export default EditList
